/**
 * 
 */
package com.shengruan.user.action;

import java.util.List;

import org.apache.log4j.Logger;

import com.shengruan.admin.jdbc.UserJdbc;
import com.shengruan.admin.vo.Product;
import com.shengruan.index.action.AuctionUtil;
import com.shengruan.user.jdbc.AutoAuctionJdbc;
import com.shengruan.user.vo.AutoAuction;

/**
 * @author liubin
 *
 */
public class AutoAuctionThread implements Runnable{
	protected static Logger logger = Logger.getLogger(AutoAuctionThread.class);
	private static boolean flag = false;
	public void run(){   
		while(true)
		{
			try{   
				Thread.sleep(8000);   
			}catch(InterruptedException e){   
				e.printStackTrace();   
			}  
			boolean result = biding();   
			if(!result)
				break;
		}
	}   

	private synchronized boolean biding(){   
		if(flag==true)
			return true;
		flag = true;
		List<Product> productList  = AuctionUtil.getList(0,2);
		if(productList.size() > 0)
		{   
			int userId = Integer.parseInt(Thread.currentThread().getName());
			Thread thread = AutoThreadUtil.get(userId);
			if(thread==null)
			{
				flag=false;
				return false;
			}
//			if(logger.isDebugEnabled())
//				logger.debug("竞拍线程正在监测->用户ID:"+userId);

			for(int i=0;i<productList.size();i++)
			{
				Product product = (Product)productList.get(i);
				String id = userId+"||"+product.getId();

				AutoAuction autoAuction = AutoAuctionUtil.get(id);

				if(autoAuction==null)	//商品不在自动竞拍商品中 ->返回
				{
					continue;
				}
					
				double startPrice = autoAuction.getStartPrice();
				int tactics = autoAuction.getTactics();
				long nowTime = System.currentTimeMillis();
				long thisAuctionEndTime = product.getThisAuctionEndTime();
				double currentPrice = product.getCurrentPrice();
				Integer bidUserId = product.getBidUserId();
				if(bidUserId!=null&&bidUserId==userId)	//如果已经是最后一个投标用户 ->返回
				{
					continue;
				}
				if(currentPrice<startPrice)		//如果没到最低的开始竞拍价格 ->返回
				{
					continue;
				}
				if(tactics==1&&(thisAuctionEndTime-nowTime)/1000>10)//10秒内随机竞拍，如果非10 ->返回
				{
					continue;
				}
				if(autoAuction.getBidNum()<=0) //如果用户标数不足，设置为 非激活状态
				{
					AutoAuctionJdbc autoAuctionJdbc = new AutoAuctionJdbc();
					autoAuctionJdbc.setState(autoAuction.getId(), 0, userId);
					AutoAuctionUtil.remove(id);
					continue;
				}
				UserJdbc userJdbc = new UserJdbc();
				String result = AuctionUtil.bidProduct(product.getId(),userJdbc.getSimpleUser(userId),autoAuction.getId());
				if("success".equals(result))
				{
					AutoAuctionJdbc autoAuctionJdbc = new AutoAuctionJdbc();
					autoAuctionJdbc.updateBidNum(autoAuction.getId());
					autoAuction.setBidNum(autoAuction.getBidNum()-1);
					AutoAuctionUtil.add(id, autoAuction);
					
				}
			}

		
		} 
		flag = false;
		return true;
	}   
}

